class_name Enemy extends CharacterBody2D


@onready var navigation_agent_2d: NavigationAgent2D = $NavigationAgent2D as NavigationAgent2D
@export var max_speed: float = 400.0
@export var acceleration: float = 1500.0
@export var deceleration: float = 1500.0
var player: Player


@onready var _player_detection_area: Area2D = $PlayerDetectionArea as Area2D


func _ready() -> void:
	if not multiplayer.is_server():
		set_physics_process(false)
		_player_detection_area.monitoring = false
		return
	var players: Array = get_tree().get_nodes_in_group("player")
	if not players.is_empty():
		player = players.pick_random()
	

func _physics_process(delta: float) -> void:
	if not is_instance_valid(player):
		return
	navigation_agent_2d.target_position = player.global_position
	if navigation_agent_2d.is_navigation_finished():
		velocity = velocity.move_toward(Vector2.ZERO, deceleration * delta)
	else:
		var next_position: Vector2 = navigation_agent_2d.get_next_path_position()
		var direction_to_next_position: Vector2 = global_position.direction_to(next_position)
		velocity = velocity.move_toward(direction_to_next_position * max_speed, acceleration * delta)
	move_and_slide()


func _on_player_detection_area_body_entered(body: Node2D) -> void:
	var _player: Player = body as Player
	if _player != null:
		_player.get_hit()
		queue_free()
		

func get_hit() -> void:
	queue_free()
